package ide.ccf.ccproject.properties;

import ide.ccf.ccproject.CCFProject;
import ide.ccf.ccproject.preferences.CCFPreferencePage;

import org.eclipse.cdt.core.envvar.IEnvironmentVariable;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.settings.model.ICConfigurationDescription;
import org.eclipse.cdt.core.settings.model.ICProjectDescription;
import org.eclipse.cdt.core.settings.model.ICResourceDescription;
import org.eclipse.cdt.internal.core.envvar.EnvironmentVariableManager;
import org.eclipse.cdt.internal.core.envvar.UserDefinedEnvironmentSupplier;
import org.eclipse.cdt.ui.newui.MultiCfgContributedEnvironment;
import org.eclipse.cdt.utils.envvar.StorableEnvironment;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.PropertyPage;

public class CCFCCPropertyPage extends PropertyPage 
{
	private static final String SEPARATOR = System.getProperty("path.separator", ";"); //$NON-NLS-1$ //$NON-NLS-2$
	ICConfigurationDescription cfg = null;
	private StorableEnvironment vars = null;
	private static final UserDefinedEnvironmentSupplier fUserSupplier = EnvironmentVariableManager.fUserSupplier;

	private Combo versioncombo;
	private Button projectFileListenerCheck;
	private int oldVersionIndex;

	/**
	 * 构造器
	 */
	public CCFCCPropertyPage() 
	{
		super();
	}
	
	/**
	 * 添加页面显示控制
	 * @param parent
	 */
	private void addControls(Composite parent) 
	{
		Composite composite = new Composite(parent, SWT.NULL);
		GridLayout layout = new GridLayout();
		layout.numColumns = 2;
		composite.setLayout(layout);
		
		GridData data = new GridData();
		data.verticalAlignment = GridData.FILL;
		data.horizontalAlignment = GridData.FILL;
		data.grabExcessHorizontalSpace = true;
		data.grabExcessVerticalSpace = true;
		composite.setLayoutData(data);
		
		Label label = new Label(composite, SWT.NONE);
		label.setText("使用的CCF版本: ");
		versioncombo = new Combo(composite, SWT.READ_ONLY);
		
		data = new GridData();
		data.horizontalAlignment = GridData.FILL;
		data.grabExcessHorizontalSpace = true;
		versioncombo.setLayoutData(data);
		
		projectFileListenerCheck = new Button(composite, SWT.CHECK);
		projectFileListenerCheck.setText("项目文件发生变化时自动执行make");
		projectFileListenerCheck.setToolTipText("当允许时，只要CCF项目文件内容发生变化或者它的任一包含发生变化均会调用make。");
		data = new GridData();
		data.horizontalAlignment = GridData.FILL;
		data.grabExcessHorizontalSpace = true;
		projectFileListenerCheck.setLayoutData(data);
	}

	/**
	 * 装载版本设置
	 */
	private void loadPersistentSettings() 
	{
		versioncombo.add("<默认>");
		
		String[] versions = CCFPreferencePage.getCCFVersions();
		
		CCFProject project = new CCFProject((IProject)getElement());
		String currentVersion = project.getVersion();
		
		versioncombo.select(0);
		
		if (versions != null) 
		{
			for (int i = 0; i < versions.length; ++i) 
			{
				versioncombo.add(versions[i]);
				
				if (versions[i].equals(currentVersion)) 
				{
					versioncombo.select(i + 1);
				}
			}
		}
		setOldVersionToSelectedVersion();
		
		projectFileListenerCheck.setSelection(project.runQMakeWhenProjectFileChanges());
	}
	
	/**
	 * 保存版本设置
	 * @return
	 */
	private boolean savePersistentSettings() 
	{
		CCFProject project = new CCFProject((IProject)getElement());
		project.setRunQMakeWhenProjectFileChanges(projectFileListenerCheck.getSelection());

		return project.setVersion(versioncombo.getItem(versioncombo.getSelectionIndex()));
	}
	
	/**
	 * 版本是否变化
	 * @return
	 */
	private boolean versionHasChanged() 
	{
		return (versioncombo.getSelectionIndex() != oldVersionIndex);
	}
	
	/**
	 * 设置旧版本为以选中版本
	 */
	private void setOldVersionToSelectedVersion()
	{
		oldVersionIndex = versioncombo.getSelectionIndex();
	}
	
	/**
	 * 创建显示内容
	 */
	protected Control createContents(Composite parent) 
	{
		Composite composite = new Composite(parent, SWT.NONE);
		GridLayout layout = new GridLayout();
		composite.setLayout(layout);
		GridData data = new GridData(GridData.FILL);
		data.grabExcessHorizontalSpace = true;
		composite.setLayoutData(data);

		addControls(composite);
		
		loadPersistentSettings();
		
		return composite;
	}

	/**
	 * 恢复默认
	 */
	protected void performDefaults() 
	{
		versioncombo.select(0);
	}
	
	/**
	 * 确认
	 */
	@SuppressWarnings("restriction")
	public boolean performOk() 
	{
		if (savePersistentSettings()) 
		{
			if (versionHasChanged()) 
			{
				//版本发生变化，工程的环境变量PATH应该改变
				CCFProject project = new CCFProject((IProject)getElement());
				String binPath = project.getBinPath();
				ICResourceDescription cfgd = null;
				ICConfigurationDescription cfgDescription = null;
			
				ICProjectDescription des = CoreModel.getDefault().getProjectDescription(project.getProject(), false);
				if(des != null)
				{
					cfgDescription = des.getDefaultSettingConfiguration();
					IPath projectPath = Platform.getLocation();
					cfgd = cfgDescription.getResourceDescription(projectPath, false);
				}
				//针对CCF增加相应路进到PATH环境变量
				ICConfigurationDescription[] cfgs = null;
				if(cfgDescription != null)
					cfgs = new ICConfigurationDescription[] {cfgDescription};
				if (cfgDescription == null && vars == null)
					vars = fUserSupplier.getWorkspaceEnvironmentCopy();
				if (cfgd == null)
					vars.createVariable("PATH", binPath,
							IEnvironmentVariable.ENVVAR_PREPEND, SEPARATOR);
				else
					for (ICConfigurationDescription cfg : cfgs) {
						MultiCfgContributedEnvironment ce = new MultiCfgContributedEnvironment();;
						ce.addVariable("PATH", binPath,
								IEnvironmentVariable.ENVVAR_PREPEND,
								SEPARATOR, cfg);
					}
	
				if (!requestFullBuild())
					return false;
				
				setOldVersionToSelectedVersion();
			}
		} 
		else 
		{
			return false;
		}
		return true;
	}

	/**
	 * 请求重新构建
	 * @return
	 */
	private boolean requestFullBuild() 
	{
		boolean accepted = false;
		Shell shell = PlatformUI.getWorkbench().getDisplay().getActiveShell();
		MessageDialog dialog = new MessageDialog(shell, "CCF版本变化", null, "某些项目的CCF版本设置已经发生改变。需要重建构建项目以使设置生效。是否现在重新构建？", MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2);
		
		switch (dialog.open()) 
		{
			case 2: 
				accepted = false; 
				break;
				
			case 0:
				(new CCFProject((IProject)getElement())).scheduleRebuild();
				accepted = true;
				break;
				
			case 1: 
				accepted = true;
				break;
		}
		return accepted;
	}
}
